<template>
  <el-card class="peak-valley-flat-analysis-wrapper card-header">
    <header>
      <div class="head">
        <div class="head-icon">
          <svg-icon icon-class="chart"></svg-icon>
        </div>
        <div>峰谷平电量电费分析</div>
      </div>
      <div><XyTimePicker></XyTimePicker></div>
    </header>
    <div class="data-energy-container" ref="chartContainer"></div>
    <div class="analysis-wrapper electricity-consumption">
      <header>峰谷平分析</header>
      <main>
        <div class="main-left">
          <div>峰期 (8:00-11:00, 18:00-23:00):</div>
          <div icon-class="dot">峰期电量:10.5kWh</div>
          <div icon-class="dot">峰期电费:¥6.30</div>
          <div icon-class="dot">占总电量:56.8%</div>
        </div>
        <div class="main-mid">
          <div>平期 (7:00-8:00, 11:00-18:00):</div>
          <div icon-class="dot">平期电量:5.8kWh</div>
          <div icon-class="dot">平期电费:¥2.32</div>
          <div icon-class="dot">占总电量:31.4%</div>
        </div>
        <div class="main-right">
          <div>谷期 (23:00-7:00):</div>
          <div icon-class="dot">谷期电量:2.2kWh</div>
          <div icon-class="dot">谷期电费:¥0.63</div>
          <div icon-class="dot">占总电量:11.9%</div>
        </div>
      </main>
    </div>
  </el-card>
</template>

<script>
import XyTimePicker from "@/components/XyTimePicker.vue";
import * as echarts from "echarts";

export default {
  components: {
    XyTimePicker,
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      window.removeEventListener("resize", this.resizeChart);
    }
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs.chartContainer;
        if (chartDom) {
          this.chart = echarts.init(chartDom);
          this.setChartOption();
          window.addEventListener("resize", this.resizeChart);
        }
      });
    },

    setChartOption() {
      // 生成时间标签（24小时）
      const labels = [];
      for (let i = 0; i < 24; i++) {
        labels.push(`${i}:00`);
      }

      // 根据时间生成峰谷平数据
      const { peakData, flatData, valleyData, totalCostData } = this.generatePeakValleyFlatTimeData(24, 'day');
      const option = {
        color: ['#EF4444', '#3B82F6', '#10B981', '#8B5CF6'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: (params) => {
            let tooltipText = `${params[0].axisValueLabel}<br/>`;
            params.forEach(param => {
              if (param.seriesIndex === 0) {
                tooltipText += `${param.marker} ${param.seriesName}: ${param.value} kWh<br/>`;
              } else if (param.seriesIndex === 1) {
                tooltipText += `${param.marker} ${param.seriesName}: ${param.value} kWh<br/>`;
              } else if (param.seriesIndex === 2) {
                tooltipText += `${param.marker} ${param.seriesName}: ${param.value} kWh<br/>`;
              } else {
                tooltipText += `${param.marker} ${param.seriesName}: ¥${param.value.toFixed(2)}<br/>`;
              }
            });
            return tooltipText;
          }
        },
        legend: {
          data: ['峰期电量', '平期电量', '谷期电量', '累计电费'],
          top: 'top'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: labels,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              color: '#9498a1',
              margin: 10,
              fontSize: 11
            },
            axisLine: {
              lineStyle: {
                color: 'rgba(148, 163, 184, 0.2)'
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '电量 (kWh)',
            nameTextStyle: {
              color: '#9498a1',
              padding: [0, 0, 0, 40],
              fontSize: 11
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(148, 163, 184, 0.1)'
              }
            },
            axisLabel: {
              color: '#9498a1',
              fontSize: 11
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: 'rgba(148, 163, 184, 0.2)'
              }
            }
          },
          {
            type: 'value',
            name: '电费 (元)',
            nameTextStyle: {
              color: '#9498a1',
              padding: [0, 0, 0, 0],
              fontSize: 11
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              color: '#9498a1',
              fontSize: 11,
              formatter: (value) => {
                return '¥' + value.toFixed(2);
              }
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: 'rgba(148, 163, 184, 0.2)'
              }
            }
          }
        ],
        series: [
          {
            name: '峰期电量',
            type: 'bar',
            stack: 'energy',
            data: peakData,
            itemStyle: {
              color: 'rgba(239, 68, 68, 0.8)', // 带透明度的颜色
              borderColor: 'rgba(239, 68, 68, 1)',
              borderWidth: 1,
               borderRadius: [6, 6, 0, 0], // 顶部圆角
              emphasis: {
                color: 'rgba(239, 68, 68, 1)' // 悬停时加深颜色
              }
            },
            yAxisIndex: 0
          },
          {
            name: '平期电量',
            type: 'bar',
            stack: 'energy',
            data: flatData,
            itemStyle: {
              color: 'rgba(59, 130, 246, 0.8)', // 带透明度的颜色
              borderColor: 'rgba(59, 130, 246, 1)',
              borderWidth: 1,
               borderRadius: [6, 6, 0, 0], // 顶部圆角
              emphasis: {
                color: 'rgba(59, 130, 246, 1)' // 悬停时加深颜色
              }
            },
            yAxisIndex: 0
          },
          {
            name: '谷期电量',
            type: 'bar',
            stack: 'energy',
            data: valleyData,
            itemStyle: {
              color: 'rgba(16, 185, 129, 0.8)', // 带透明度的颜色
              borderColor: 'rgba(16, 185, 129, 1)',
              borderWidth: 1,
              borderRadius: [6, 6, 0, 0], // 顶部圆角
              emphasis: {
                color: 'rgba(16, 185, 129, 1)' // 悬停时加深颜色
              }
            },
            yAxisIndex: 0
          },
          {
            name: '累计电费',
            type: 'line',
            data: totalCostData,
            itemStyle: {
              color: '#8B5CF6',
            },
            lineStyle: {
              width: 2
            },
            smooth: true,
            showSymbol: true,
            symbol: 'circle',
            symbolSize: 10,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(139, 92, 246, 0.2)' },
                { offset: 1, color: 'rgba(139, 92, 246, 0)' }
              ])
            },
            yAxisIndex: 1
          }
        ]
      };

      this.chart.setOption(option);
    },

    // 根据时间维度生成峰谷平数据
    generatePeakValleyFlatTimeData(count, range) {
      const peakData = [];
      const flatData = [];
      const valleyData = [];
      const totalCostData = [];
      
      // 根据时间范围确定数据量级
      let baseMultiplier = 1;
      if (range === 'month') {
        baseMultiplier = 30;
      } else if (range === 'year') {
        baseMultiplier = 365;
      }
      
      // 生成数据
      for (let i = 0; i < count; i++) {
        // 模拟峰谷平时段分布
        // 对于日视图，我们根据小时精确分配
        let peakValue = 0, flatValue = 0, valleyValue = 0;
        
        if (range === 'day') {
          // 日视图：基于小时的峰谷平分布
          const hour = i;
          // 峰期：8:00-11:00, 18:00-23:00
          if ((hour >= 8 && hour <= 11) || (hour >= 18 && hour <= 23)) {
            peakValue = this.getRandomData(1, 0.8 * baseMultiplier, 2.0 * baseMultiplier)[0];
            flatValue = 0;
            valleyValue = 0;
          }
          // 平期：7:00-8:00, 11:00-18:00
          else if ((hour >= 7 && hour < 8) || (hour > 11 && hour < 18)) {
            flatValue = this.getRandomData(1, 0.5 * baseMultiplier, 1.2 * baseMultiplier)[0];
            peakValue = 0;
            valleyValue = 0;
          }
          // 谷期：23:00-7:00
          else {
            valleyValue = this.getRandomData(1, 0.1 * baseMultiplier, 0.4 * baseMultiplier)[0];
            peakValue = 0;
            flatValue = 0;
          }
        } else {
          // 月/年视图：随机分配峰谷平时段比例
          const total = this.getRandomData(1, 0.5 * baseMultiplier, 2.0 * baseMultiplier)[0];
          // 峰期占55%，平期占30%，谷期占15%（大致比例）
          peakValue = total * 0.55 * (0.9 + Math.random() * 0.2);
          flatValue = total * 0.30 * (0.9 + Math.random() * 0.2);
          valleyValue = total - peakValue - flatValue;
        }
        
        peakData.push(parseFloat(peakValue.toFixed(2)));
        flatData.push(parseFloat(flatValue.toFixed(2)));
        valleyData.push(parseFloat(valleyValue.toFixed(2)));
        
        // 计算电费（峰期0.6元/kWh，平期0.4元/kWh，谷期0.3元/kWh）
        const cost = peakValue * 0.6 + flatValue * 0.4 + valleyValue * 0.3;
        totalCostData.push(parseFloat(cost.toFixed(2)));
      }
      
      return { peakData, flatData, valleyData, totalCostData };
    },

    // 生成随机数据的工具函数
    getRandomData(count, min, max) {
      return Array.from({ length: count }, () => 
        parseFloat((Math.random() * (max - min) + min).toFixed(2))
      );
    },

    resizeChart() {
      if (this.chart) {
        setTimeout(() => {
          this.chart.resize();
        }, 100);
      }
    },
  }
};
</script>

<style scoped lang="scss">
@import "./styles/common.scss";
.peak-valley-flat-analysis-wrapper.card-header {
  .head {
    .head-icon {
      background-color: #fee2e2;
      color: #ef4444;
    }
  }
  .data-energy-container {
    width: 100%;
    height: 400px;
    margin: 15px 0;
  }
  .electricity-consumption {
    width: 100%;
    color: #b91c1c;
    background-color: rgba(254, 242, 242, 0.8);
    main {
      margin-top: 10px;
      display: flex;
      .main-left,
      .main-mid,
      .main-right {
        width: 33%;
        padding: 10px;
      }
    }
  }
}
</style>